#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'libb@anchent.com'


def main():
    fr = None
    try:
        # 使用open打开文件
        fr = open("../python_base/python_turtle.py", 'r', encoding='utf-8')
        # 一次性读取整个文件
        print(fr.read())
        print("*" * 100)

        # for-in循环逐行读取
        with open("../python_base/python_turtle.py", 'r', encoding='utf-8') as f:
            for line in f:
                print(line, end='')
        print()
        print("*" * 100)

        # 通过with关键字指定文件对象的上下文环境并在离开上下文环境时自动释放文件资源
        with open("../python_base/python_turtle.py", 'r', encoding='utf-8') as f:
            print(f.readline())  # 读取一行文件
            print(f.readlines())  # readlines()按行读取文件到列表中

        print("*" * 100)
        # 写入文件
        with open('../test.py', mode='w', encoding='utf-8') as fw:
            fw.write(fr.read())

        print("*" * 100)
        # 读写二进制文件
        with open("../assets/004.jpg", 'rb') as frb:
            data = frb.read()
            print(data)
        with open("../assets/004.jpg", 'wb') as frb:
            print(frb.write(data))

    except FileNotFoundError:
        print("无法打开指定的文件")
    except LookupError:
        print("指定编码错误")
    except UnicodeDecodeError:
        print("读取文件时解码错误")
    finally:
        if fr:
            # 读完文件后要手动关闭文件
            fr.close()


if __name__ == '__main__':
    main()
